package com.srit.vgt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.srit.vgt.common.response.VgtPage;
import com.srit.vgt.common.utils.JSONUtils;
import com.srit.vgt.entity.City;
import com.srit.vgt.entity.District;
import com.srit.vgt.entity.Market;
import com.srit.vgt.entity.MarketTran;
import com.srit.vgt.main.DaoInject;
import com.srit.vgt.service.IMarketService;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MarketServiceImpl extends DaoInject implements IMarketService {

    @Override
    public VgtPage allMarket(VgtPage vgtPage, String cityId, String districtId) {
        Market market = new Market();
        market.setCityId(cityId);
        market.setDistrictId(districtId);
        return VgtPage.build(marketDao.findAll(Example.of(market),VgtPage.getPageable(vgtPage)));
    }

    @Override
    public JSONObject marketById(String id) {
        Market market = marketDao.getById(id);
        LocalDate today = LocalDate.now();
        List<MarketTran> allByDateIsBetween = marketTranDao.findAllByDateIsBetweenAndMarketId(today.plusDays(-8).toString(), today.plusDays(-1).toString(), id);
        JSONObject marketJson = JSONUtils.toJSONObject(market);
        marketJson.put("trans", allByDateIsBetween);
        return marketJson;
    }

    @Override
    public JSONArray areaAll() {
        List<City> cityList = cityDao.findAll();
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(cityList));
        Map<String, List<District>> dMap = districtDao.findAll().stream().collect(Collectors.groupingBy(District::getCityId));
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject city = jsonArray.getJSONObject(i);
            city.put("districtList", dMap.get(city.getString("cityId")));
        }

        return jsonArray;
    }
}
